from core.decorators import render
from django.conf import settings
from models import WallRecord, VKUser
from django.contrib.csrf.middleware import csrf_exempt
import codecs
from core.libs.poster.encode import multipart_encode
from core.libs.poster.streaminghttp import register_openers
from core.libs import vkontakte
import urllib2
import urllib
import json
import time

RESPONSE_CODE_SUCCESS = 0
RESPONSE_CODE_ERROR = 1

@render(type="json")
def send_notifications(request):

	try:

		vk = vkontakte.API("2023356", "thdXZZOEaK4hUKu9Q2Am")
		vk.secure.sendNotification(
			timestamp = "%s" % int(time.time()),
			uids = "11757838",
			message = "---->"
		)

		return {
			'code': RESPONSE_CODE_SUCCESS
		}
		
	except Exception, e:
		return {
			'code': RESPONSE_CODE_ERROR,
			'message': "%s" % e
		}

@render(type="json")
def get_wall_item(request):

    try:
        pk = request.REQUEST.get('id', None)
        record = WallRecord.objects.get(pk = pk)
        return {
            'img': record.image,
            'link': record.url
        }

    except Exception, e:
        return {
            'code': RESPONSE_CODE_ERROR,
            'message': 'Error in GET_WALL_ITEM'
        }
        
        
@csrf_exempt
@render(type="json")
def add_user(request):
    try:
        uid = request.REQUEST.get('uid', None)
		
	if not VKUser.objects.filter(uid=uid).count():
	    VKUser.objects.create(
	        uid = uid
	    )
		
        return {
            'code': RESPONSE_CODE_SUCCESS
        }

    except Exception, e:
        return {
            'code': RESPONSE_CODE_ERROR
        }	
        
        
@csrf_exempt
@render(type="json")
def post_to_wall(request):
    try:
    	url = request.REQUEST.get('url', '')#.split('/')
    	photo = request.REQUEST.get('photo', '').split('/')
    	file_name = u"%s/%s" % ("http://img.izismile.com", "/".join(photo[3:len(photo)]))
        urllib.urlretrieve(file_name, "/tmp/wall.jpg")
    	
    	register_openers()
       	datagen, headers = multipart_encode({"photo": open("/tmp/wall.jpg", "rb")})
       	rq = urllib2.Request(url, datagen, headers)
       	response = urllib2.urlopen(rq).read()
       	record = WallRecord.objects.create(
       		image = request.REQUEST.get('photo', ''),
       		url = request.REQUEST.get('link', '')
       	)
    	
    	#data = {
        #	'photo': open(file_name)
        #}
        #response = urllib2.urlopen(url, data)
    	
    	#response = post_multipart(
    	#	url[2],
    	#	"/%s" % url[3],
    	#	fields = (),
    	#	files = [
    	#		('photo', file_name, codecs.open(file_name, encoding="utf-8", errors="ignore").read())
    	#	]
    	#)
    
        return {
        	'api': json.loads(response),
        	'pid': record.pk
    	}

    except Exception, e:
    	import traceback
        return {
            'code': RESPONSE_CODE_ERROR,
            'message': traceback.format_exc()
        }

@render("crossdomain.xml")
def cross(request):
	return {}
